<template>
  <gw3d-scene-control
    ref="gwEarth"
    class="scene-content"
    gw-viewer-path="./GWViewer/GWViewer.js"
    :zoom="3"
    @ready="readyEarth"
  >
    <!--            <gw3d-tdt-layer-->
    <!--              :zIndex="1"-->
    <!--              :url="'https://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=04fc3689ef85a8e0479df5f1fc8f5ace'"-->
    <!--              :visible="true"-->
    <!--            >-->
    <!--            </gw3d-tdt-layer>-->
    <!--            <gw3d-tdt-layer-->
    <!--              :zIndex="2"-->
    <!--              :visible="true"-->
    <!--              :url="'https://t0.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=04fc3689ef85a8e0479df5f1fc8f5ace'"-->
    <!--            ></gw3d-tdt-layer>-->


    <!--基础功能-->
    <gw3d-roaming
      ref="sceneControl"
      :wholeMapExtent="wholeMapExtent"
      :home="home"
    ></gw3d-roaming>


    <!-- 罗盘导航 -->
    <cesiumNavigation v-if="cesiumNavigationVisible" @emitResetMap="emitResetMap"
                      @emitSwitchiMap="emitSwitchiMap"></cesiumNavigation>
    <!--    底部工具栏-->
    <div class="time-line" id="time-line">
      <div class="closeBtn el-icon-close" title="close" v-show="timeClose" @click="closeTimeBtn"></div>
    </div>
    <div
      class="menu-container animate__animated animate__fadeInLeft"
      v-loading="loading"
      element-loading-text="Loading"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      :style="{ width: `${LeftWidth}px`, left: queryVisible ? 0 : `-${LeftWidth}px` ,height:!resultVisible?'calc(100vh - 100px)':'550px'}"
    >
      <query v-if="!resultVisible" @trackSimulation="trackSimulation" ref="queryRef"
             @transitPrediction="transitPrediction" @clearAll="clearAll"></query>
      <tableResult v-if="resultVisible"
                   :collapseBtnList="collapseBtnList"
                   @handleBackHome="transitPrediction"
                   @showRightLegend="showRightLegend"
                   @handleCurrentChange="handleCurrentChange"

                   @showStatic="showStatic" />

      <div class="left-arrow-contract" @click="queryVisible=!queryVisible"></div>
    </div>
    <div class="satics-con" v-if="barXdata.length>0" :style="{ right: showStaticsVisible ? '0px' : `-380px` }">
      <div class="left-arrow-contract-lengned left-arrow-contract-saticsCon" v-show="barXdata.length>0"
           @click="changeStatic"></div>
      <div class="title">
        Transit statistics
      </div>
      <div class="echart-con pt5">
        <BarChart
          id="barChart"
          height="260px"
          width="100%"
          :barXdata="barXdata"
          :barYdata="barYdata"
          :commonData="commonData"
        />
      </div>
    </div>
    <right-legend :legendData="legendData" v-show="legendData.length>0"></right-legend>
    <router-link class="configBtn" :to="{ path: '/configMange' }">Configuration</router-link>
  </gw3d-scene-control>
</template>
<script>
import tableResult from "@/components/table-result";
import rightLegend from "@/components/rightLegend";
import query from "./leftModes/Query";
import cesiumNavigation from "@/components/cesiumNavigation";
import { extractRGBValues } from "@/utils/public";
import bbox from "@turf/bbox";
import { flyto } from "@/utils/utils";
import { getLiteCoverageStatistics, getSatelliteRoute, getStripSimulation, getStripsInfo } from "@/api";
import WKT from "terraformer-wkt-parser";
import BarChart from "@/components/BarChart.vue";
import { addDays, format } from "date-fns";

let regionLayer = null;
export default {
  data() {
    return {
      legendData: [],
      collapseBtnList: [],
      resultVisible: false,
      lengendVisible: false,
      wholeMapExtent: [67.14, 0.703, 149.765, 55.57],
      home: {
        center: [113.48414979625014, 22.871612287500074]
      },
      loading: false,
      LeftWidth: 460,
      queryVisible: true,
      resetDataForm: {
        id: "1",
        name: "Orbit prediction 1",
        nodeType: "Optical",
        newForm: {
          geometry: "",
          groupVal: "Resolution",
          groupType: "Resolution",
          scenetime: [format(new Date(), "yyyy-MM-dd hh:mm:ss"), format(addDays(new Date(), 2), "yyyy-MM-dd hh:mm:ss")],
          province: "",
          uploadFiles: null,
          satellite: [],
          checkDataList: [],
          sateCheckList: []

        }
      },
      cesiumNavigationVisible: false,
      isConfig: true,
      isObservation: true,
      gridData: [],
      resultList: {},
      earth: null,
      timeLine: null,
      loadingObj: {
        lock: true,
        text: "正在加载....",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      },
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      baseLayers: [],
      czmlLayerId: null,
      czmlLayer: null,
      tableInfo: [],
      sateInfo: [],
      measureType: "",
      baseMapSwitch: "",
      panelShow: false,
      baseSwitchArr: [],
      fullscreen: false,
      imgBase: "",
      visible: false,
      currentRow: {},
      saomiaoArea: null,
      baseServiceUrl: "",
      annotationServiceUrl: "",
      showStaticsVisible: false,
      getUserShape: null,
      maskStyle: {
        fill: "rgba(255, 0, 0, 0)",
        stroke: {
          color: "red",
          width: 2
        },
        circle: {
          radius: 6,
          fill: "red",
          stroke: {
            width: 1,
            color: "red"
          }
        }
      },
      barXdata: [],
      barYdata: [],
      commonData: [],
      productId: "",
      geoFeature: null,
      geoFeatureYellow: null,
      selectFeatureId: "",
      timeClose: false
    };
  },
  components: {
    tableResult,
    BarChart,
    rightLegend,
    query,
    cesiumNavigation
  },
  provide() {
    return {
      addGeometry: this.addGeometry,
      clearRegionLayer: this.clearRegionLayer,
      resultVisible: this.resultVisible
    };
  },
  methods: {
    currentData() {
      const allData = JSON.parse(localStorage.getItem("collapseData")) || [];
      if (this.productId) {
        return allData.find(item => item.id === this.productId);
      }
    },
    clearBarData() {
      this.barXdata = [];
      this.barYdata = [];
      this.commonData = [];
      this.showStaticsVisible = false;
    },
    readyEarth(windowEarth) {
      const that = this;
      if (windowEarth) {
        window.earth = windowEarth;
        this.cesiumNavigationVisible = true;
        this.$refs.gwEarth.mapReady(() => {
          if (window.earth) {
            that.czmlLayer = new GWViewer.CzmlFeature({}, window.earth);
            that.czmlLayerId = this.czmlLayer.id;
            sessionStorage.setItem("resetDataForm", JSON.stringify(this.resetDataForm));
          }
        });
      }
    },
    changeStatic() {
      if (this.barXdata.length > 0) {
        this.showStaticsVisible = !this.showStaticsVisible;
      }

    },
    clearAll() {
      this.clearTrajectory();
      this.clearSaomiaoGuojing();
      this.legendData = [];
      this.showStaticsVisible = false;
    },
    /**
     * 轨迹仿真*/
    async trackSimulation(matchedItem) {
      this.loading = true;
      if (Object.keys(matchedItem).length === 0) {
        return;
      }
      if (matchedItem.newForm.geometry == "") {
        this.$message.warning("Please select the area range");
        return;
      }
      this.initTime(matchedItem.newForm.scenetime[0], matchedItem.newForm.scenetime[1], matchedItem);
    },
    /**
     *获取最新轨迹
     */
    async initRoute(matchedItem, inIsoTime, outIsoTime) {
      try {
        const { newForm } = matchedItem;
        const params = [
          {
            boundaryWkt: newForm.geometry,
            startTime: newForm.scenetime[0],
            endTime: newForm.scenetime[1],
            satelliteIds: newForm.satellite
          }
        ];
        const res = await getSatelliteRoute(params);
        this.clearTrajectory();
        if (res && Array.isArray(res[0]) && res[0].length > 0) {
          res[0].forEach(({ czml, satelliteCode, orbitalColor }) => {
            this.createRoute(czml, orbitalColor, satelliteCode);
          });
        }
        this.loading = false;
        this.legendData = res[0].map(({ satelliteCode, orbitalColor }) => {
          return {
            label: satelliteCode,
            color: orbitalColor
          };
        });
        //加载之前清除
        if (this.timeLine) {
          this.timeLine.destroy();
          this.timeLine = null;
        }
        const startTime = (new Date(inIsoTime)).toISOString();
        const endTime = (new Date(outIsoTime)).toISOString();
        this.timeClose = true;
        this.timeLine = new GWViewer.TimeLine(
          {
            parentsID: "time-line",
            startTime: startTime,
            endTime: endTime,
            multiplier: 1
          },
          window.earth
        );
        this.timeLine.display();
        this.timeLine._timeLine.zoomTo(this.timeLine._start, this.timeLine._stop);
        if (this.timeLine) {
          document.getElementById("time-line-gw-20190722").style.width = "780px";
          document.getElementsByClassName("cesium-timeline-main")[0].style.backdropFilter = "blur(5px)";
        }
      } catch (error) {
        console.error("Error initializing route:", error);
        // 在这里可以添加更多的错误处理逻辑
      }
    },
    createRoute(czml, orbitalColor, satelliteCode) {
      const [r, g, b] = extractRGBValues(orbitalColor);
      this.czmlLayer.addData({
        data: czml,
        style: {
          path: {
            color: GWViewer.Color.fromBytes(r, g, b, 255)
          },
          label: {
            showBackground: true,
            backgroundColor: GWViewer.Color.BLOCK,
            fillColor: new GWViewer.Color(1, 1, 1, 1),
            font: "40px",
            text: satelliteCode
          }
        }
      });
    },
    initTime(inIsoTime, outIsoTime, matchedItem) {
      this.initRoute(matchedItem, inIsoTime, outIsoTime);

    },
    /**过境预测
     * */
    async transitPrediction(visible, data) {
      if (visible) {
        this.loading = true;
        const res = await getStripsInfo(data);
        if (Array.isArray(res) && res.length > 0) {
          if (this.$refs.queryRef) {
            this.$refs.queryRef.handleCleanDraw();
          }
          this.resultVisible = visible;
          this.loading = false;
          if (this.resultVisible) {
            this.collapseBtnList = res.map((item, index) => {
              return {
                tableData: item.strips,
                label: item.paramGroupName,
                id: index + 1,
                routeDtos: item.routeDtos,
                productId: item.productId,
                coverageRate: (item.coverageRate).toFixed(2),
                selectFeature: null,
                routeColor: item.routeColor
              };
            });
          } else {
            this.clearSaomiaoGuojing();
            this.clearBarData();
            this.legendData = [];
          }

        } else {
          this.loading = false;
          this.$message.warning("warning");
        }
      } else {
        this.resultVisible = false;
        this.clearSaomiaoGuojing();
        this.barXdata = [];
        this.legendData = [];
        this.clearTrajectory()
      }


    },
    /**
     * 显示统计图
     * */
    async showStatic(visible, item) {
      this.clearBarData();
      if (!visible) {
        return;
      }
      this.productId = item.productId;
      const currentData = this.currentData();
      const params = {

        "boundaryWkt": currentData.newForm.geometry,
        "endTime": currentData.newForm.scenetime[1],
        "satelliteIds": currentData.newForm.satellite,
        "startTime": currentData.newForm.scenetime[0]
      };
      const res = await getLiteCoverageStatistics(params);

      if (res.length > 0) {

        res.forEach(item => {
          if (item.strips > 0) {
            this.barXdata.push(item.satelliteCode);
            this.barYdata.push({
              value: item.coverageRate,
              ...item
            });
            this.commonData.push({
              coverageRate: item.coverageRate,
              strips: item.strips
            });
          }

        });
        if (this.barXdata.length > 0) {
          this.$nextTick(() => {
            this.showStaticsVisible = visible;
          });
        } else {
          this.$message.warning("No Data");
        }
      }
    },
    clearSaomiaoGuojing() {
      if (this.saomiaoArea) {
        this.saomiaoArea.then(function(dataSource) {
          window.earth.viewer.dataSources.remove(dataSource);
        });
        this.saomiaoArea = null;
      }
      let selectFeatures = this.getLayerById(this.selectFeatureId);
      if (selectFeatures) {
        selectFeatures.clean();
        this.selectFeatureId = null;
      }
      if (this.geoFeatureYellow) {
        const selectF = this.getLayerById(this.selectFeatureId);
        if (selectF) {
          selectF.clean();
        }
        this.geoFeatureYellow.destroy();
        this.geoFeatureYellow.clean();
        this.geoFeatureYellow = null;
      }

    },
    /**
     *  当前扫描的轨迹
     * */
    handleCurrentChange(val) {
      if (!val) {
        return;
      }
      if (this.saomiaoArea) {
        this.saomiaoArea.then(function(dataSource) {
          window.earth.viewer.dataSources.remove(dataSource);
        });
        this.saomiaoArea = null;
      }
      let selectFeature = this.getLayerById(this.selectFeatureId);
      if (selectFeature) {
        selectFeature.clean();
      }
      selectFeature = new GWViewer.GeoJsonFeature({}, window.earth);
      this.selectFeatureId = selectFeature.id;
      let dataSource = this.geoFeatureYellow.getDataSourceById(val.id);
      //获取过境geojson数组对象
      // const [r, g, b] = extractRGBValues(val.orbitalColor);
      if (dataSource) {
        //记载图斑
        selectFeature.addData({
          id: val.id,
          fillColor: GWViewer.Color.fromBytes(153, 51, 250, 0),
          outLineColor: GWViewer.Color.GOLD,
          outLineWidth: 2,
          data: val.stripGeoJson
        });

      }
      this.currentRow = val;
      this.getTrajectory(val);
    },
    /*显示右侧图例信息*/
    showRightLegend(data, productId, item) {

      if (data.length === 0) {
        this.clearSaomiaoGuojing();
        this.clearRegionLayer();
        this.barXdata = [];
        this.legendData = [];
        return;
      }
      this.productId = productId;
      this.showStatic(true, item);
      //绘制红色边框
      const currentData = this.currentData();
      this.paintArea(currentData.newForm.geometry);
      const matchedItem = this.collapseBtnList.find(item => item.productId === productId);
      if (!matchedItem) {
        return;
      }
      // console.log("黄色区域");
      this.clearTrajectory();
      for (const { satelliteCode, orbitalColor, czml } of matchedItem.routeDtos) {
        this.createRoute(czml, orbitalColor, satelliteCode);
      }
      this.legendData = matchedItem.routeColor.map(({ orbitalColor, satelliteCode }) => {
        return {
          label: satelliteCode,
          color: orbitalColor
        };
      });
      this.clearSaomiaoGuojing();
      this.geoFeatureYellow = new GWViewer.GeoJsonFeature({}, window.earth);
      for (let j = 0; j < data.length; j++) {
        const items = data[j];
        const [r, g, b] = extractRGBValues(items.orbitalColor);
        //绘制黄色区域
        this.geoFeatureYellow.addData({
          id: items.id,
          fillColor: GWViewer.Color.fromBytes(r, g, b, 100),
          outLineColor: GWViewer.Color.fromBytes(r, g, b, 100),
          lineWidth: 2,
          data: items.stripGeoJson
        });
      }
    },
    // 切换二三维地图底图
    emitSwitchiMap(type) {
      let earth = window.earth;
      if (type == 2) {
        earth._viewer.scene.morphTo2D(0);
      } else if (type == 3) {
        earth._viewer.scene.morphTo3D(0);
      }
    },
    emitResetMap() {
      let lon = 113;
      let lat = 29.999999999999993;
      let height = 3499999.9999999073;
      // const { lon, lat, height } = window.earth.getCameraInfo();
      flyto(lon, lat, height, window.earth, 2);
    },
    getMatchedItem() {
      const currentData = this.currentData();
      if (Object.keys(currentData).length === 0) {
        return;
      }
      return currentData;
    },
    //开始进行轨迹模拟
    async getTrajectory(val) {
      this.currentRow = val;
      if (Object.keys(this.currentRow).length > 0) {
        this.clearGuojing();
        const { satelliteNodeId, stripIndex } = val;
        const matchedItem = this.getMatchedItem();
        const boundaryWkt = matchedItem.newForm.geometry;
        const startTime = matchedItem.newForm.scenetime[0];
        const endTime = matchedItem.newForm.scenetime[1];
        const res = await getStripSimulation({
          boundaryWkt,
          startTime,
          endTime,
          satelliteId: satelliteNodeId,
          index: stripIndex
        });
        //加载扫描区域
        if (res.length > 0) {
          res[0].clock.multiplier = 1;
          this.saomiaoArea = window.earth.viewer.dataSources.add(Cesium.CzmlDataSource.load(res)
          );
        }
      } else {
        this.$message.error("请选择模拟卫星");

      }
    },
    getLayerById(id) {
      return window.earth.findLayerByID(id);
    },
    /**清除轨迹
     * */
    clearTrajectory() {
      let czmLayer = this.getLayerById(this.czmlLayer.id);
      if (czmLayer) {
        czmLayer.clean();
      }
      if (this.timeLine) {
        this.timeLine.destroy();
        this.timeLine = null;
        this.timeClose = false;
      }
    },
    /**
     * 清除过境
     * */
    clearGuojing() {
      //清除时间轴
      if (this.timeLine) {
        this.timeLine.destroy();
        this.timeLine = null;
        this.timeClose = false;
      }
    },

    paintArea(boundaryWkt) {
      this.clearSaomiaoGuojing();
      this.addGeometry(WKT.parse(boundaryWkt));
    },
    addGeometry(geometry) {
      this.clearRegionLayer();
      if (window.earth) {
        regionLayer = new GWViewer.GeoJsonFeature({}, window.earth);
        this.addDataToGeojsonnLayer(geometry);
      }

    },
    addDataToGeojsonnLayer(data) {
      if (regionLayer) {
        regionLayer.addData({
          id: "1235",
          data: data,
          fillColor: GWViewer.Color.fromBytes(255, 255, 255, 0),
          outLineColor: GWViewer.Color.fromBytes(247, 0, 58, 255),
          outLineWidth: 2
        });
        let extent = bbox(data);
        let param = 0.5;
        let weDiff = extent[2] - extent[0];
        let snDiff = extent[3] - extent[1];
        //GeoJSON外接矩形
        window.earth.flyToTarget({
          rectangle: {
            west: extent[0] * 1 - weDiff * param,
            south: extent[1] * 1 - snDiff * param,
            east: extent[2] * 1 + weDiff * param,
            north: extent[3] * 1 + snDiff * param
          },
          time: 3
        });
        this.isLoadingFun(false);
      }


    },
    isLoadingFun(status = true) {
      const loading = this.$loading(this.loadingObj);
      if (!status) {
        loading.close();
      }
    },
    //删除加载区域
    clearRegionLayer() {
      if (regionLayer) {
        regionLayer.destroy();
        regionLayer = null;
      }
    },
    /**
     * 关闭轨迹和仿真
     * */
    closeTimeBtn() {
      //关闭仿真
      this.clearGuojing();
      //关闭轨迹
      this.clearTrajectory();
      //  关闭图例
      this.legendData = [];
    }
  }
};
</script>

<style lang="scss" scoped>
.time-line {
  position: absolute;
  width: 850px;
  height: 60px;
  z-index: 9;
  bottom: 24px;
  left: 50%;
  margin-left: -425px;

  .closeBtn {
    width: 20px;
    height: 20px;
    background: #444;
    z-index: 100;
    position: absolute;
    top: -20px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
    cursor: pointer;
    left: -23px;
  }
}

.cesium-timeline-bar {
  backdrop-filter: blur(5px) !important;
}

.scene-content {
  position: relative;
  overflow: hidden;


  .left-content {
    position: absolute;
    left: 15px;
    top: 15px;
    z-index: 999;

    .position-input {
      margin-bottom: 10px;
      width: 320px;
    }
  }

  .area-code-content {
    position: absolute;
    z-index: 9999;
    right: 559px;
    top: 27px;
  }

  .tool-action-content {
    position: absolute;
    right: 15px;
    top: 15px;
    z-index: 10000;

    div {
      margin-top: 10px;
    }
  }
}

.baseMapSwitch {
  position: absolute;
  right: 0;
  top: 75px;
}

.right-control {
  position: absolute;
  right: 24px;
  bottom: 24px;
  z-index: 999;
  box-sizing: border-box;
  width: 2.1rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: rgba(1, 1, 38, .3);
  border-radius: 0.13rem;
  box-shadow: var(--el-box-shadow);
  color: #fff;
  backdrop-filter: blur(5px);

  > i {
    padding: 0.4rem;
    cursor: pointer;
    font-size: 1.13rem;

    &:hover,
    &.activeMesure {
      color: #00C2CE;
    }
  }

}

.baseMapCon {
  position: absolute;
  bottom: 24px;
  right: 70px;
  z-index: 200;
}

::v-deep .el-tabs--border-card > .el-tabs__content {
  padding-bottom: 5px;
}

.configBtn {
  position: absolute;
  bottom: 20px;
  left: 15px;
  z-index: 100;
  background: url("~@/assets/imgs/configurabtn.png");
  width: 137px;
  height: 50px;
  display: flex;
  justify-content: center;
  cursor: pointer;
  align-items: center;
  text-decoration: none;
  color: #fff;
  font-size: 14px;
}

.satics-con {
  width: 380px;
  height: 340px;
  background: #1F222A;
  box-shadow: -2px 0px 4px 0px rgba(5, 11, 30, 0.4);
  position: absolute;
  top: 0px;
  right: 0px;
  z-index: 200;
  transition: all 0.7s ease 0ms;

  .title {

    font-weight: 500;
    font-size: 20px;
    color: #FFFFFF;
    margin: 15px 0px 0 15px;
  }

  .back-icon {
    width: 30px;
    height: 40px;
    background: #303339;
    border-radius: 6px 0px 0px 6px;
    position: absolute;
    top: 20px;
    right: 380px;
    font-size: 16px;
    color: #fff;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 200;
  }

  .topTitle {
    width: 100%;
    height: 60px;
    box-sizing: border-box;
    padding: 10px;
    background: #071019;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
  }

  .echart-con {
    width: 100%;
    height: 220px;

  }
}

.left-arrow-contract-lengned {
  position: absolute;
  bottom: 31%;
  height: 60px;
  width: 16px;
  transform: rotate(180deg);
  right: 380px;
  z-index: 2010;
  background-image: url('@/assets/imgs/left_arrow2.png');
  background-size: 100% 100%;
  cursor: pointer;
}

.left-arrow-contract-saticsCon {
  top: 0px;
  bottom: 0%;
}

.menu-container {
  position: absolute;
  top: 0px;
  left: 0px;
  z-index: 1000;
  width: 460px;
  height: calc(100vh - 100px);
  box-sizing: border-box;
  background: #1F222A;
  box-shadow: 2px 0px 4px 0px rgba(5, 11, 30, 0.4);
  //transition: all .3s ease-out;
  transition: left .3s ease-out;
  -webkit-transition: left .3s ease-out
}

.left-arrow-contract {
  position: absolute;
  top: 35%;
  transform: translateY(-50%);
  height: 60px;
  width: 16px;
  right: -16px;
  z-index: 200;
  background-image: url('@/assets/imgs/left_arrow2.png');
  background-size: 100% 100%;
  cursor: pointer;
}

</style>
